package com.example.sunnyweather.logic.ui.weather

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Build.VERSION.SDK_INT
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.sunnyweather.R
import com.example.sunnyweather.SunnyWeatherApplication.Companion.simpleDateFormat
import com.example.sunnyweather.logic.model.DailyResponse
import com.example.sunnyweather.logic.model.RealtimeResponse
import com.example.sunnyweather.logic.model.Weather
import com.example.sunnyweather.logic.model.getSky
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.life_index.*
import kotlinx.android.synthetic.main.now.*
import java.text.SimpleDateFormat
import java.util.*


class WeatherActivity : AppCompatActivity() {
    val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN Activity全屏，状态栏依然显示
        // View.SYSTEM_UI_FLAG_LAYOUT_STABLE 这个标志来帮助你的应用维持一个稳定的布局
        // 这些设置用位运算 or 或者 | 来连起来
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        // 设置状态栏透明
        window.statusBarColor = Color.TRANSPARENT

        setContentView(R.layout.activity_weather)

        // 刚开始设置weatherLayout不可见
        weatherLayout.visibility = View.INVISIBLE

        // 点进天气界面的intent中取出经纬度用于之后的天气查询，同时也传入了地名
        if (viewModel.locationLng.isEmpty()) {
            viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
        }
        if (viewModel.locationLat.isEmpty()) {
            viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
        }
        if (viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }

        viewModel.weatherLiveData.observe(this, Observer { result ->
            var weather = result.getOrNull()

            // 因为API暂时没有token，这里先自己造了个Weather显示出来再说
            weather = generateWeather()
            if (weather != null) {
                showWeatherInfo(weather)
                Toast.makeText(this, "最近更新于：${simpleDateFormat.format(Date())}", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show()
                result.exceptionOrNull()?.printStackTrace()
            }
            // 显示完成，刷新关闭
            swipeRefresh.isRefreshing = false
        })

        // 设置刷新相关
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
        refreshWeather()
        swipeRefresh.setOnRefreshListener {
            refreshWeather()
        }

        // 导航按钮，也就是切换城市
        navBtn.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }
        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerStateChanged(newState: Int) {}
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}
            override fun onDrawerOpened(drawerView: View) {}
            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE)
                        as InputMethodManager
                manager.hideSoftInputFromWindow(drawerView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)
            }
        })

    }

    fun refreshWeather(){
        viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
        swipeRefresh.isRefreshing = true
    }

    private fun generateWeather(): Weather? {

        val realTime = RealtimeResponse.Realtime("HAIL",8f,
            RealtimeResponse.AirQuality(RealtimeResponse.AQI(12f)))
        val lifeIndex = DailyResponse.LifeIndex(
            listOf(DailyResponse.LifeDescription("易感冒")),
            listOf(DailyResponse.LifeDescription("不易洗车")),
            listOf(DailyResponse.LifeDescription("18")),
            listOf(DailyResponse.LifeDescription("保暖衣")))

        val daily = DailyResponse.Daily(
            listOf(
                DailyResponse.Temperature(16f,7f),
                DailyResponse.Temperature(16f,7f),
                DailyResponse.Temperature(16f,7f),
                DailyResponse.Temperature(16f,7f)),
            listOf(
                DailyResponse.Skycon("HAIL",Date()),
                DailyResponse.Skycon("HAIL",Date()),
                DailyResponse.Skycon("HAIL",Date()),
                DailyResponse.Skycon("HAIL",Date())),
            lifeIndex)

        return Weather(realTime,daily)
    }

    private fun showWeatherInfo(weather: Weather) {

        val realtime = weather.realtime
        val daily = weather.daily

        // 填充now.xml布局中的数据
        placeName.text = viewModel.placeName
        val currentTempText = "${realtime.temperature.toInt()} ℃"
        currentTemp.text = currentTempText
        currentSky.text = getSky(realtime.skycon).info
        val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()}"
        currentAQI.text = currentPM25Text
        nowLayout.setBackgroundResource(getSky(realtime.skycon).bg) //设置背景为当前天气

        // 填充forecast.xml布局中的数据

        forecastLayout.removeAllViews() // 清除预报布局里的所有item，也就是旧天气显示内容
        val days = daily.skycon.size
        // 循环把每一天的信息放到forecast_item 然后添加到 forecastLayout父布局里
        for (i in 0 until days) {
            val skycon = daily.skycon[i]
            val temperature = daily.temperature[i]
            val view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                forecastLayout, false)
            // 这里之所以用findViewById，因为这里的东西都是item，不是一个，是多个，每个都在不同的view里
            val dateInfo = view.findViewById(R.id.dateInfo) as TextView
            val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
            val skyInfo = view.findViewById(R.id.skyInfo) as TextView
            val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView

            val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            dateInfo.text = simpleDateFormat.format(skycon.date)
            val sky = getSky(skycon.value)
            skyIcon.setImageResource(sky.icon)
            skyInfo.text = sky.info
            val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃"
            temperatureInfo.text = tempText

            // 把处理好的item添加到forecastLayout里
            forecastLayout.addView(view)
        }

        // 填充life_index.xml布局中的数据，只取当天的数据
        val lifeIndex = daily.lifeIndex
        coldRiskText.text = lifeIndex.coldRisk[0].desc
        dressingText.text = lifeIndex.dressing[0].desc
        ultravioletText.text = lifeIndex.ultraviolet[0].desc
        carWashingText.text = lifeIndex.carWashing[0].desc

        // 设置weatherLayout可见
        weatherLayout.visibility = View.VISIBLE
    }
}
